
//
//  UICollectionView+PlaceholdView.m
//  beichoo_N_ios
//
//  Created by 卢仕彤 on 2017/9/25.
//  Copyright © 2017年 陈健. All rights reserved.
//

#import "UICollectionView+PlaceholdView.h"
#import <objc/runtime.h>


@implementation NSObject (swozzle)

+ (void)swizzleInstanceSelector:(SEL)originalSel WithSwizzledSelector:(SEL)swizzledSel {
    // 进行方法的替换
    
    Method originMethod = class_getInstanceMethod(self, originalSel);
    Method swizzedMehtod = class_getInstanceMethod(self, swizzledSel);
    BOOL methodAdded = class_addMethod(self, originalSel, method_getImplementation(swizzedMehtod), method_getTypeEncoding(swizzedMehtod));
    if (methodAdded)
    {
        class_replaceMethod(self, swizzledSel, method_getImplementation(originMethod), method_getTypeEncoding(originMethod));
    }else{
        method_exchangeImplementations(originMethod, swizzedMehtod);
    }
}
@end

@implementation UICollectionView (PlaceholdView)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [self swizzleInstanceSelector:@selector(reloadData) WithSwizzledSelector:@selector(ff_reloadData)];
    });
}

- (void)setPlaceHolderView:(UIView *)placeHolderView {
    objc_setAssociatedObject(self, @selector(placeHolderView), placeHolderView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (UIView *)placeHolderView {
      return objc_getAssociatedObject(self, @selector(placeHolderView));
}

- (void)ff_reloadData {
    [self ff_checkEmpty];
    [self ff_reloadData];
}

- (void)ff_checkEmpty {
    BOOL isEmpty = YES;
    id <UICollectionViewDataSource> src = self.dataSource;
    NSInteger sections = 1;
    if ([src respondsToSelector:@selector(numberOfSectionsInCollectionView:)])
    {
        sections = [src numberOfSectionsInCollectionView:self];
    }
    for (int i = 0; i < sections; i++) {
        @autoreleasepool {
            NSInteger rows = [src collectionView:self numberOfItemsInSection:i];
            if (rows) {
                isEmpty = NO;
            }
        }
    }
    if (isEmpty) {
        [self.placeHolderView removeFromSuperview];
        [self addSubview:self.placeHolderView];
    }else{
        [self.placeHolderView removeFromSuperview];
    }
}



@end
